package com.shiny.concurrency4java.singleton;

import com.shiny.concurrency4java.util.Constant;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

@Slf4j
public class SingletonExample1 {

    private enum Singleton{
        INSTANCE;
        private SingletonExample1 instance;

        Singleton(){
            instance = new SingletonExample1();
        }
        public SingletonExample1 getInstance(){
            return instance;
        }
    }

    private SingletonExample1(){
        log.info("SingletonExample1 function start");
    }

    public static SingletonExample1 getInstance(){
        return Singleton.INSTANCE.getInstance();
    }

    public static void main(String[] args) throws Exception{
        ExecutorService executorservice = Executors.newCachedThreadPool();
        final Semaphore semaphore = new Semaphore(Constant.threadTotal);
        final CountDownLatch countdownlatch = new CountDownLatch(Constant.clientTotal);
        for(int i = 0; i < Constant.clientTotal; i++ ) {
            executorservice.execute(()-> {
                try{
                    semaphore.acquire();
                    SingletonExample1.getInstance();
                    semaphore.release();
                }catch (Exception e) {
                    e.printStackTrace();
                }
                countdownlatch.countDown();
            });
        }
        countdownlatch.await();
        return;
    }

}
